package com.qf.game.websocket.entity;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Integer == int
 *
 * 棋盘类
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class ChessBoard implements Serializable {

    private Integer[][] board;

    /**
     * 构造方法 传入棋局的长宽
     * @param len
     */
    public ChessBoard(int len){
        board = new Integer[len][len];
    }

    /**
     * 落子的方法，如果落子成功返回true，否则返回false
     */
    public boolean go(int x, int y, int color){
        if (board[x][y] != null) {
            return false;
        }
        board[x][y] = color;
        return true;
    }

    /**
     * 是否胜利
     * @return
     */
    public boolean isWin(int x, int y, Integer color){

        //----------横向的判断逻辑-----------
        int count = 1;
        //往左判断
        int a = x;
        while(--a >= 0 && board[a][y] == color)count++;
        //往右判断
        a = x;
        while(++a < board.length && board[a][y] == color)count++;
        if (count >= 5) return true;

        //---------纵向的判断逻辑-------------
        count = 1;
        //往上判断
        int b = y;
        while(--b >= 0 && board[x][b] == color)count++;
        //往下判断
        b = y;
        while(++b < board.length && board[x][b] == color)count++;
        if (count >= 5) return true;

        //---------左斜向的判断-------------
        count = 1;
        a = x;
        b = y;
        while(--a >= 0 && --b >= 0 && board[a][b] == color)count++;
        a = x;
        b = y;
        while(++a < board.length && ++b < board.length && board[a][b] == color)count++;
        if (count >= 5) return true;

        //----------右斜向的判断------------
        count = 1;
        a = x;
        b = y;
        while(++a < board.length && --b >= 0 && board[a][b] == color)count++;
        a = x;
        b = y;
        while(--a >= 0 && ++b < board.length && board[a][b] == color)count++;
        if (count >= 5) return true;

        return false;
    }

    /**
     * 返回当前棋局中所有的落子信息
     * @return
     */
    public List<Point> getAllPoint(){
        List<Point> points = new ArrayList<>();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] != null) {
                    Point point = new Point();
                    point.setX(i);
                    point.setY(j);
                    point.setColor(board[i][j]);
                    points.add(point);
                }
            }
        }
        return points;
    }

    /**
     * 落子信息
     */
    @Data
    public static class Point implements Serializable{
        private int x;
        private int y;
        private int color;
    }
}
